﻿
using Asxsyd92Core.Utils;
using Asxsyd92Core.Utils.Data.SQLServer;
using WebOSCore.Models;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebOS.Bll;
using WebOS.Modle;
using WebOS.Modle.WorkFlowExecute;
using WebOS.Dal;
using WebOS.Modle.WorkFlowCustomEventParams;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Authorization;
using IdentityModel;

namespace WebOSCore.Controllers.Api
{

    public class FormDesignController : Controller
    {
        private readonly IHubContext<ChatHub> _hubContext;
        public FormDesignController(IHubContext<ChatHub> hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpPost]
        [Route("api/FormDesign/FormDesignYL")]
        public  string FormDesignYL(string html="")
        {
            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/webos/page/from/FDsubmit.html";
            Encoding code = Encoding.GetEncoding("utf-8");
            // 读取模板文件
            // string temp = HttpContext.Current.Server.MapPath("Text.htm");
            StreamReader sr = null;
            string str = "";
            try
            {
                sr = new StreamReader(path, code);
                str = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                //sr.Close();
                return exp.Message; ;

            }

            // 替换内容
            // 这时,模板文件已经读入到名称为str的变量中了
            str = str.Replace("$FDsubmit$", html);
            // 写文件
            try
            {

                return str;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                // sw.Close();
            }
        }
        [HttpPost]
        [Authorize]
        [Route("api/FormDesign/FormDesignHtml")]
        public string FormDesignHtml(string html,string name, bool type,string data)
        {
          
            var r = name;
            if (type) { name = "Debug/" + name; } else { name = "Release/" + name; }
            var tl = FormDesign(html);
            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/webos/page/from/" + name + ".html";
            // 判断文件是否存在，不存在则创建，否则读取值显示到窗体
            data= data.Replace("_sys_url", "/webos/page/from/" + name + ".html");
    
          var fmdata= SqlFromData.GetFromData("SysFormDesign",new {Tab= r }).FirstOrDefault();
            if (fmdata != null)
            {
                var objdata = Models.Unity.ObjModel(fmdata);
                data= data.Replace("_sys_id", objdata.FirstOrDefault(c => c.Key.ToString() == "ID").Value.ToString());
                SqlFromData.SaveFromData("SysFormDesign", data);
            }
            else {
                data=data.Replace("_sys_id", Guid.Empty.ToString());
                SqlFromData.SaveFromData("SysFormDesign", data);
            }
            if (!System.IO.File.Exists(path))
            {
                System.IO.File.Create(path).Dispose();

                FileStream wfs = new FileStream(path, FileMode.Create);
                //获得字节数组
                byte[] datas = System.Text.Encoding.UTF8.GetBytes(tl);
                //开始写入
                wfs.Write(datas, 0, datas.Length);
                //清空缓冲区、关闭流
                wfs.Flush();
                wfs.Close();
            }

            else
            {
                //清空
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
                fs.Seek(0, SeekOrigin.Begin);//文本的起点
                fs.SetLength(0);//从起点写入0个值
                fs.Close();
                FileStream wfs = new FileStream(path, FileMode.Create);
                //获得字节数组
                byte[] dataS = System.Text.Encoding.UTF8.GetBytes(tl);
                //开始写入
                wfs.Write(dataS, 0, dataS.Length);
                //清空缓冲区、关闭流
                wfs.Flush();
                wfs.Close();
            }
            return "/webos/page/from/" + name + ".html";
        }

        public static string FormDesign(string html)
        {

            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/webos/page/from/FDsubmit.html";
            Encoding code = Encoding.GetEncoding("utf-8");
            // 读取模板文件
            // string temp = HttpContext.Current.Server.MapPath("Text.htm");
            StreamReader sr = null;
            string str = "";
            try
            {
                sr = new StreamReader(path, code);
                str = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                //sr.Close();
                return exp.Message; ;

            }

            // 替换内容
            // 这时,模板文件已经读入到名称为str的变量中了
            str = str.Replace("$FDsubmit$", html);
            // 写文件
            try
            {

                return str;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                // sw.Close();
            }
        }


        [HttpPost]
        [Route("api/Form/FormSave")]
        public string FormSave(string query,string table, string data,string params1)
        {

          var js=  SendFolwForm(query, table,  data, params1);
            //var user = User.Claims.FirstOrDefault(c => c.Type == "id").Value;
            //var toUser = WebOSCore.Models.ChatHub.ConnectedUsers.FirstOrDefault(c => c.id == user);
            //if (toUser != null)
            //{
            //    await _hubContext.Clients.Client(toUser.ConnectionId).SendAsync("receivePrivateMessage", toUser.username, toUser.avatar, toUser.id, "friend", "成功发送信息");
            //}

            return JSONhelper.ToJson(new { code = 0, msg = js.Messages, count = 1, Success = js.IsSuccess });
        }

        
      [HttpPost]
        [Authorize]
        [Route("api/Form/FormCommonTaskSave")]
        public  string FormCommonTaskSave(string table, string data)
        {

            int tag = 0;
            var id = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.SaveFromData(table, data);
            if (id == Guid.Empty)
            {
                return JSONhelper.ToJson(new { msg = "添加失败！", Success = false });
            }
            var DAS = CommonTaskDal.Instance.Get(new { InstanceID = id });
            var jsonData = LitJSONCore.JsonMapper.ToObject(data);
            var user = User.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Id).Value;
            var username = User.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Name).Value;
            if (DAS == null)
            {
                WebOS.Modle.CommonTask task = new WebOS.Modle.CommonTask();
                task.ID = Guid.NewGuid();
                task.InstanceID = id;
                task.t_Table = table;
                task.SenderName = username;
                task.SenderID = user.ToGuid();
                task.AddTime = System.DateTime.Now;
               
                try
                {
                    task.Title = jsonData["Title"].ToString();
                }
                catch
                {
                    task.Title = "标题不错在！";
                }
                tag = CommonTaskDal.Instance.Insert(task);

            }
            else
            {
                try
                {
                    DAS.Title = jsonData["Title"].ToString();
                }
                catch
                {
                    DAS.Title = "标题不错在！";
                }
                tag = CommonTaskDal.Instance.Update(DAS);

            }
            if (tag > 0)
            {
                return JSONhelper.ToJson(new { msg = "添加成功！", Success = true });
            }
            else return JSONhelper.ToJson(new { msg = "添加失败！", Success = false });
        }
        [HttpGet]
        [Route("api/Form/FormTable")]
        public string FormTable(string table)
        {
            //第一步查询SysFormDesign是否已经存在已有表单
          var da=  SqlFromData.GetFromData("SysFormDesign", new { Tab = table }).FirstOrDefault();
            if (da != null)
            {
                return JSONhelper.ToJson(new { code = 0, msg = "1", data = da });

            }
            else {
                var list = SqlFromData.GetTableStructure(table);
                return JSONhelper.ToJson(new { code = 0, msg = "-1", data = list });
            }
         
           


        }


        public Result  SendFolwForm(string query, string table, string data,string params1) {

            var querys = JsonConvert.DeserializeObject<Query>(query);
            if (querys == null) { return null; }
            //string params1 = querys.params1;
            string issign = querys.issign;
            string comment = querys.comment;
            string flowid = querys.flowid;
            Guid instanceid = querys.instanceid.ToGuid();

            string taskid = querys.taskid;
            string stepid = querys.stepid;
            string groupid = querys.groupid;

            var opationJSON = LitJSONCore.JsonMapper.ToObject(params1);
            string opation = opationJSON["type"].ToString().ToLower();

         //WorkFlow bworkFlow = new WorkFlow();
         //  WorkFlowTask btask = new WorkFlowTask();
          //WorkFlowDelegation bworkFlowDelegation = new WorkFlowDelegation();
          //Organize borganize = new Organize();
          // Users busers = new Users();
          var wfl=  WebOS.Dal.WorkFlowDal.Instance.Get(flowid.ToGuid());
            string error = "";
            var wfInstalled = WorkFlowBll.Instance.GetWorkFlowRunModel(wfl.RunJSON,out error);
            if (wfInstalled == null)
            {
                return null;

            }

            //流程标题
            string titleField = querys.Form_TitleField;
            string title = querys.titleField;

            Execute execute = new Execute();
            execute.Comment = comment.IsNullOrEmpty() ? "" : comment.Trim();
            switch (opation)
            {
                case "submit":
                    execute.ExecuteType = EnumType.ExecuteType.Submit;
                    break;
                case "save":
                    execute.ExecuteType = EnumType.ExecuteType.Save;
                    break;
                case "back":
                    execute.ExecuteType = EnumType.ExecuteType.Back;
                    break;
                case "completed":
                    execute.ExecuteType =EnumType.ExecuteType.Completed;
                    break;
                case "redirect":
                    execute.ExecuteType = EnumType.ExecuteType.Redirect;
                    break;
            }
            var user = User.Claims.FirstOrDefault(c => c.Type == "id").Value;
            execute.FlowID = flowid.ToGuid();
            execute.GroupID = groupid.ToGuid();
            execute.InstanceID = instanceid.ToString();
            execute.IsSign = "1" == issign;
            execute.Note = "";
            execute.Sender = UsersDal.Instance.Get(user.ToGuid());
            execute.StepID = stepid.IsGuid() ? stepid.ToGuid() : wfInstalled.FirstStepID;
            execute.TaskID = taskid.ToGuid();
            execute.Title = title ?? "";
           
            LitJSONCore.JsonData stepsjson = opationJSON["steps"];
            if (stepsjson.IsArray)
            {
                foreach (LitJSONCore.JsonData step in stepsjson)
                {
              
                    string id = step["id"].ToString();
                    string member = step["member"].ToString();
                    Guid gid;
                    if (id.IsGuid(out gid))
                    {
                        switch (execute.ExecuteType)
                        {
                            case EnumType.ExecuteType.Submit:
                     
                                execute.Steps.Add(gid, OrganizeBll.Instance.GetAllUsers(member));
                                break;
                            case EnumType.ExecuteType.Back:
                                execute.Steps.Add(gid, new List<Users>());
                                break;
                            case EnumType.ExecuteType.Save:
                                break;
                            case EnumType.ExecuteType.Completed:
                                break;
                            case EnumType.ExecuteType.Redirect:
                                break;
                        }
                    }
                    if (execute.ExecuteType == EnumType.ExecuteType.Redirect)
                    {
          
                        execute.Steps.Add(Guid.Empty, OrganizeBll.Instance.GetAllUsers(member));
                    }
                }
            }

            WorkFlowCustomEventParams eventParams = new WorkFlowCustomEventParams();
            eventParams.FlowID = execute.FlowID;
            eventParams.GroupID = execute.GroupID;
            eventParams.StepID = execute.StepID;
            eventParams.TaskID = execute.TaskID;
            eventParams.InstanceID = execute.InstanceID;
           
            //保存业务数据 "1" != Request.QueryString["isSystemDetermine"]:当前步骤流转类型如果是系统判断，则先保存数据，在这里就不需要保存数据了。
            if (execute.ExecuteType == EnumType.ExecuteType.Save ||
                execute.ExecuteType == EnumType.ExecuteType.Completed ||
                "1" != querys.isSystemDetermine
            )
            {
               instanceid  = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.SaveFromData(table, data); 
              
                if (execute.InstanceID.ToGuid().IsEmptyGuid())
                {
                    execute.InstanceID = instanceid.ToString();
                    eventParams.InstanceID = instanceid.ToString();
                }
            }
    
          //  Response.Write("执行参数：" + params1 + "<br/>");

            var steps = wfInstalled.Steps.Where(p => p.ID == execute.StepID);
            foreach (var step in steps)
            {
                //步骤提交前事件
                if (!step.Event.SubmitBefore.IsNullOrEmpty() &&
                    (execute.ExecuteType == EnumType.ExecuteType.Submit
                    || execute.ExecuteType == EnumType.ExecuteType.Completed))
                {
                    object obj = WorkFlowTaskBll.Instance.ExecuteFlowCustomEvent(step.Event.SubmitBefore.Trim(), eventParams);
                   // Response.Write(string.Format("执行步骤提交前事件：({0}) 返回值：{1}<br/>", step.Event.SubmitBefore.Trim(), obj.ToString()));
                }
                //步骤退回前事件
                if (!step.Event.BackBefore.IsNullOrEmpty() && execute.ExecuteType == EnumType.ExecuteType.Back)
                {
                    object obj = WorkFlowTaskBll.Instance.ExecuteFlowCustomEvent(step.Event.BackBefore.Trim(), eventParams);
                   // Response.Write(string.Format("执行步骤退回前事件：({0}) 返回值：{1}<br/>", step.Event.BackBefore.Trim(), obj.ToString()));
                }
            }

            ////处理委托
            //foreach (var executeStep in execute.Steps)
            //{
            //    for (int i = 0; i < executeStep.Value.Count; i++)
            //    {
            //        Guid newUserID = bworkFlowDelegation.GetFlowDelegationByUserID(execute.FlowID, executeStep.Value[i].ID);
            //        if (newUserID != Guid.Empty && newUserID != executeStep.Value[i].ID)
            //        {
            //            executeStep.Value[i] = busers.Get(newUserID);
            //        }
            //    }
            //}

            var reslut = WorkFlowTaskBll.Instance. Execute(execute);
          //  Response.Write(string.Format("处理流程步骤结果：{0}<br/>", reslut.IsSuccess ? "成功" : "失败"));
           // Response.Write(string.Format("调试信息：{0}", reslut.DebugMessages));
            string msg = reslut.Messages;
            string logContent = string.Format("处理参数：{0}<br/>处理结果：{1}<br/>调试信息：{2}<br/>返回信息：{3}",
                params1,
                reslut.IsSuccess ? "成功" : "失败",
                reslut.DebugMessages,
                reslut.Messages
                );

          //  RoadFlow.Platform.Log.Add(string.Format("处理了流程({0})", wfInstalled.Name), logContent, RoadFlow.Platform.Log.Types.流程相关);

            foreach (var step in steps)
            {
                //步骤提交后事件
                if (!step.Event.SubmitAfter.IsNullOrEmpty() &&
                    (execute.ExecuteType == EnumType.ExecuteType.Submit
                    || execute.ExecuteType == EnumType.ExecuteType.Completed))
                {
                    object obj = WorkFlowTaskBll.Instance.ExecuteFlowCustomEvent(step.Event.SubmitAfter.Trim(), eventParams);
                    //Response.Write(string.Format("执行步骤提交后事件：({0}) 返回值：{1}<br/>", step.Event.SubmitAfter.Trim(), obj.ToString()));
                }
                //步骤退回后事件
                if (!step.Event.BackAfter.IsNullOrEmpty() && execute.ExecuteType == EnumType.ExecuteType.Back)
                {
                    object obj = WorkFlowTaskBll.Instance.ExecuteFlowCustomEvent(step.Event.BackAfter.Trim(), eventParams);
                  //  Response.Write(string.Format("执行步骤退回后事件：({0}) 返回值：{1}<br/>", step.Event.BackAfter.Trim(), obj.ToString()));
                }
            }

            //归档
            if (execute.ExecuteType == EnumType.ExecuteType.Submit
                || execute.ExecuteType == EnumType.ExecuteType.Completed)
            {
                var currentsteps = wfInstalled.Steps.Where(p => p.ID == execute.StepID);
                if (currentsteps.Count() > 0 && currentsteps.First().Archives == 1)
                {
                    string flowName, stepName;
                    string formHtml =querys. form_body_div_textarea;
                    string commentHtml = querys.form_commentlist_div_textarea;
                    //stepName = bworkFlow.GetStepName(execute.StepID, execute.FlowID, out flowName, true);
                    //string archivesContents = new RoadFlow.Platform.WorkFlowForm().GetArchivesString(formHtml, commentHtml);
                    WorkFlowArchives wfr = new WorkFlowArchives();
                    wfr.Comments = commentHtml;
                    //wfr.Contents = archivesContents;
                    //wfr.FlowID = execute.FlowID;
                    //wfr.FlowName = flowName;
                    wfr.GroupID = execute.GroupID;
                    wfr.ID = Guid.NewGuid();
                    wfr.InstanceID = execute.InstanceID;
                    wfr.StepID = execute.StepID;
                  //  wfr.StepName = stepName;
                  //  wfr.Title = title.IsNullOrEmpty() ? flowName + "-" + stepName : title;
                    wfr.TaskID = execute.TaskID;
                    wfr.WriteTime = DateTime.Now;
                   // WorkFlowArchivesDal..Add(wfr);
                }
            }

          //  Response.Write("<script type=\"text/javascript\">alert('" + msg + "');top.mainDialog.close();</script>");

            if (reslut.IsSuccess)
            {
                //判断是打开任务还是关闭窗口
    
            }
            return reslut;
        }
        [HttpGet]
        [Route("api/Form/GetFormData")]
        public string GetFormData(string table, string where)
        {
           // return JSONhelper.ToJson(SqlFromData.GetNoMoldeWhere(table, where);
            return JSONhelper.ToJson(UsersDal.Instance.GetNoMoldeWhere(table, where));
        }
        [HttpGet]
        [Route("api/Form/GetDictionaryByID")]

        public string GetDictionaryByID(Guid id)
        {
            return DictionaryBll.Instance.GetDictionaryByID(id);
        }
        [HttpGet]
        [Route("api/Common/GetCommon")]

        public string GetCommon(string table, string where)
        {
            //任意一个实体类进行调用
            //表必传，where 条件不能为 ColumnsName 为字段 ColumnType为值  js 如下
            // steps = [];
            // steps.push({ TableName: "test", ColumnsName: "Title", ColumnType: "值" });
            //c#调用
            //List <Asxsyd92Core.Utils.Data.SQLServer.SetTable> sets= new List<Asxsyd92Core.Utils.Data.SQLServer.SetTable>();
            //sets.Add(new Asxsyd92Core.Utils.Data.SQLServer.SetTable { ColumnsName="Title",ColumnType="值" });
            //UsersDal.Instance.GetNoMoldeWhere(table, sets.ToJson());
            return JSONhelper.ToJson(UsersDal.Instance.GetNoMoldeWhere(table, where));

        }
    }

}

